#include <iostream>
#include <string>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include "Log.hpp"
#include "pthread.hpp"
using namespace LogModule;
using namespace PthreadModel;
int sockfd = 0;
std::string ser_ip;
uint16_t ser_port;
pthread_t id;
void sed()
{
    struct sockaddr_in server;
    socklen_t len = sizeof(server);
    memset(&server, 0, sizeof(ser_port));
    server.sin_family = AF_INET;
    server.sin_port = ntohs(ser_port);
    server.sin_addr.s_addr = inet_addr(ser_ip.c_str());
    while (true)
    {
        std::string in;
        std::cout << "please enter# ";
        std::getline(std::cin, in);
        int n = sendto(sockfd, in.c_str(), in.size(), 0, (struct sockaddr *)&server, len);
        (void)n;
    }
}
void rsv()
{
    while (true)
    {
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        char buffer[1024];
        int m = recvfrom(sockfd, buffer, sizeof(buffer), 0, (struct sockaddr *)&peer, &len);
        if (m > 0)
        {
            buffer[m] = 0;
            std::cerr<< buffer<<std::endl;//文件描述符2
        }
        if(buffer=="QUIT")
        {
            pthread_cancel(id);
            break;
        }
    }
}
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        LOG(LogLevel::ERROR) << "启动错误 client ip serve_port";
        exit(1);
    }
    ser_ip = argv[1];
    ser_port = std::stoi(argv[2]);
    // 创建网络套接字
    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        LOG(LogLevel::ERROR) << "打开网络文件错误";
        exit(1);
    }

    // 创建线程
    pthread sender(sed);
    pthread resver(rsv);
    

    resver.start();
    sender.start();

    id=resver.Id();
    resver.Join();
    sender.Join();
    return 0;
}